package com.ifast.common.base;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.baomidou.mybatisplus.plugins.Page;
import com.ifast.common.utils.HttpContextUtils;
import com.ifast.common.utils.ShiroUtils;
import com.ifast.sys.domain.RoleDO;
import com.ifast.sys.domain.UserDO;
import com.ifast.sys.service.RoleService;

/**
 * 
 * <pre>
 * </pre>
 * 
 * <small> 2018年2月25日 | Aron</small>
 */
public abstract class AdminBaseController {

	protected Logger log = LoggerFactory.getLogger(this.getClass());

    protected final String SUPER_ADMIN="超级用户角色";

    protected final String AUDIT_ADMIN="审核员";

    protected final String ENTER_ADMIN="录入员";


    @Autowired
    RoleService roleService;

    public UserDO getUser() {
        return ShiroUtils.getSysUser();
    }

    public Long getUserId() {
        return getUser().getId();
    }

    public static Subject getSubjct() {
        return SecurityUtils.getSubject();
    }

    public String getUsername() {
        return getUser().getUsername();
    }
    public Integer getRole(){
        List<Long> ids = getUser().getroleIds();
        // 添加用户必然选择角色
        long roleId = 0;
        int authorStatus = 0;
        if (ids != null && ids.size() > 0) {
            roleId = ids.get(0);
            RoleDO role = roleService.selectById(roleId);
            if (role != null) {
                if (SUPER_ADMIN.equals(role.getRoleName())) {
                    authorStatus = 2;
                } else if (AUDIT_ADMIN.equals(role.getRoleName())) {
                    authorStatus = 1;
                } else if (ENTER_ADMIN.equals(role.getRoleName())) {
                    authorStatus = 0;
                }
            }
        }
        return authorStatus;
    }

    /**
     * <pre>
     * 自动获取分页参数，返回分页对象page
     * </pre>
     * 
     * <small> 2018年4月15日 | Aron</small>
     * 
     * @param e
     * @return
     */
    public <E> Page<E> getPage(Class<E> e) {
        int pageNumber = getParaToInt("pageNumber", 1);
        int pageSize = getParaToInt("pageSize", 10);
        return new Page<>(pageNumber, pageSize);
    }

    private int getParaToInt(String key, int defalut) {
        String pageNumber = HttpContextUtils.getHttpServletRequest().getParameter(key);
        if (StringUtils.isBlank(pageNumber)) {
            return defalut;
        }
        return Integer.parseInt(pageNumber);
    }
}